package com.github.catvod.spider;

import android.text.TextUtils;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.Json;
import com.github.catvod.utils.Util;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网站:https://dyds.app、https://dyds.la
 * @author:fs
 * 电影大师
 */
public class Dyds extends Spider {
    private String siteUrl="https://dyds.one/";

    private String categoryUrl=siteUrl.concat("index.php/vod/type/id/");

    private String searchUrl=siteUrl.concat("index.php/vod/search/page");


    private Map<String, String> getHeaders() {
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", Util.CHROME);
        return header;
    }

    @Override
    public String homeContent(boolean filter) throws Exception {
        List<com.github.catvod.bean.Class> classes = new ArrayList<>();
        String[] typeIdList = {"/", "1", "3", "4", "23","2","21","26"};
        String[] typeNameList = {"首页", "电影", "电视剧", "动漫", "综艺", "纪录片", "伦理"};
        for (int i = 0; i < typeNameList.length; i++) {
            classes.add(new Class(typeIdList[i], typeNameList[i]));
        }
        return Result.string(classes, new ArrayList<>());
    }

    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        if (tid.equals("/")){
            // 首页
            Document doc = Jsoup.parse(OkHttp.string(siteUrl, getHeaders()));
            List<Vod> list=parseCatagoryHtmlVod(doc);
            return Result.string(Integer.parseInt(pg),Integer.parseInt(pg)+1,20,list.size(),list);
        }
        String categoryUrl=this.categoryUrl.concat(tid).concat("/page/").concat(pg).concat(".html");
        System.out.println(categoryUrl);
        Document doc = Jsoup.parse(OkHttp.string(categoryUrl, getHeaders()));
        List<Vod> list=parseCatagoryHtmlVod(doc);
        return Result.string(Integer.parseInt(pg),Integer.parseInt(pg)+1,20,list.size(),list);
    }

    private List<Vod> parseCatagoryHtmlVod(Document doc) {
        Elements lilist = doc.select("ul.stui-vodlist > li");
        List<Vod> list = new ArrayList<>();
        for (Element li : lilist) {
            String pic = li.select("a").first().attr("data-original");
            String id = li.select("a").first().attr("href");
            String title = li.select(".title").text();
            String remark = li.select("span.pic-text.text-right").text();
            list.add(new Vod(id, title, pic, remark));
        }
        return list;
    }



    @Override
    public String detailContent(List<String> ids) throws Exception {
        String url=Util.removeUrlTrailingSlash(siteUrl).concat(ids.get(0));
        Document doc = Jsoup.parse(OkHttp.string(url, getHeaders()));
        Elements info = doc.select("div.stui-content__detail");
        String name = info.select("h1.title").text();
        String pic = info.select("div.stui-content__thumb > a.pic > img").attr("data-original");
        String remark = info.select("p.data").get(1).text().replace("状态：", "");
        String area = info.select("p.data").get(2).text().replace("地区：", "");
        String year = info.select("p.data").get(4).text().replace("年份：", "");
        String de = info.select("p.data").get(4).text().replace("导演：", "");
        String desc = info.select("p.desc").text().replace("简介：", "");
        Elements from = doc.select("div.stui-pannel__head > ul.nav >li");
        System.out.println(from);
        List<String> fromList = new ArrayList<>();
        for (Element element : from) {
            fromList.add(element.text());
        }
        Elements playList = doc.select("div.tab-content > div.tab-pane.fade");
        List<String> playUrl = new ArrayList<>();
        for (Element play : playList) {
            Elements playlink = play.select("li");
            StringBuilder stringBuilder = new StringBuilder();
            for (Element link : playlink) {
                String playName = link.select("a").text();
                String linkUrl =  link.select("a").attr("href");
                // 如果是最后一个元素不加#号
                if (playlink.get(playlink.size() - 1).equals(link)){
                    stringBuilder.append(playName).append("$").append(linkUrl);
                }else {
                    stringBuilder.append(playName).append("$").append(linkUrl).append("#");
                }
            }
            playUrl.add(stringBuilder.toString());
        }
        Vod vod = new Vod();
        vod.setVodId(ids.get(0));
        vod.setVodPic(pic);
        vod.setVodName(name);
        vod.setVodPic(pic);
        vod.setVodRemarks(remark);
        vod.setVodPlayFrom(TextUtils.join("$$$", fromList));
        vod.setVodPlayUrl(TextUtils.join("$$$", playUrl));
        vod.setVodYear(year);
        vod.setVodArea(area);
        vod.setVodActor(de);
        vod.setVodDirector(de);
        vod.setVodContent(desc);
        return Result.string(vod);
    }


    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        // 进行请求播放
        String html = OkHttp.string(Util.removeUrlTrailingSlash(siteUrl).concat(id), getHeaders());
        String result = Util.findByRegex("var player_aaaa=(.*)</script>", html, 1);
        JSONObject jsonObject = Json.parseJson(result);
        String url = jsonObject.getString("url");
        return Result.get().url(url).header(getHeaders()).string();
    }


    // 默认进行的第一页搜索
    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        Document doc = Jsoup.parse(OkHttp.string(searchUrl.concat("1/wb").concat(Util.encodeURIComponent(key)).concat(".html"), getHeaders()));
        List<Vod> list = parseCatagoryHtmlVod(doc);
        return Result.string(list);
    }

    // 进行第二页搜索
    @Override
    public String searchContent(String key, boolean quick, String pg) throws Exception {
        Document doc = Jsoup.parse(OkHttp.string(searchUrl.concat(pg).concat("/wb").concat(Util.encodeURIComponent(key)).concat(".html"), getHeaders()));
        List<Vod> list = parseCatagoryHtmlVod(doc);
        return Result.string(Integer.parseInt(pg),Integer.parseInt(pg)+1,20,list.size(),list);
    }
}
